package com.tek.ding.faceding.ui.book;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.tek.ding.faceding.R;
import com.tek.ding.faceding.base.BaseActivity;
import com.tek.ding.faceding.bean.BaseBean;
import com.tek.ding.faceding.bean.Members;
import com.tek.ding.faceding.presenter.book.BookContract;
import com.tek.ding.faceding.presenter.book.BookModel;
import com.tek.ding.faceding.presenter.book.BookPresenter;
import com.tek.ding.faceding.utils.Constants;
import com.tek.ding.faceding.utils.MyToastUtils;
import com.tek.ding.faceding.utils.NepUtil;
import com.tek.ding.faceding.utils.SPUtils;

import cn.bertsir.zbar.CameraPreview;
import cn.bertsir.zbar.Qr.ScanResult;
import cn.bertsir.zbar.Qr.Symbol;
import cn.bertsir.zbar.QrConfig;
import cn.bertsir.zbar.ScanCallback;
import cn.bertsir.zbar.utils.QRUtils;
import cn.bertsir.zbar.view.ScanLineView;
import cn.bertsir.zbar.view.ScanView;
import cn.bertsir.zbar.view.VerticalSeekBar;

public class ScanBookActivity extends BaseActivity<BookPresenter> implements BookContract.BookView, SensorEventListener {

    private Members members;

    private CameraPreview cp;
    private SoundPool soundPool;
    private ScanView sv;
    private ImageView iv_flash;
    private ImageView iv_album;
    private static final String TAG = "QRActivity";
    private TextView tv_des, tvMemberNameValue, tvReadBookValue, tvReadDayValue;
    private QrConfig options;
    private VerticalSeekBar vsb_zoom;
    //用于检测光线
    private SensorManager sensorManager;
    private Sensor sensor;

    private String storeUid;

    public static void startActivity(Context context, Members members) {
        context.startActivity(new Intent(context, ScanBookActivity.class)
                .putExtra(INTENT_DATA, members));
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_scan_book;
    }

    @Override
    protected String setTitleName() {
        return "扫码添加读书记录";
    }

    @Override
    protected BookPresenter createPresenter() {
        return new BookPresenter(new BookModel(), this);
    }

    @Override
    protected void init() {
        members = getIntent().getParcelableExtra(INTENT_DATA);

        storeUid = SPUtils.getString(Constants.STORE_UID, "");

        options = new QrConfig.Builder()
                .setDesText("")//扫描框下文字
                .setShowDes(false)//是否显示扫描框下面文字
                .setShowLight(false)//显示手电筒按钮
                .setShowTitle(false)//显示Title
                .setShowAlbum(false)//显示从相册选择按钮
                .setNeedCrop(false)//是否从相册选择后裁剪图片
                .setCornerColor(Color.parseColor("#1E90FF"))//设置扫描框颜色
                .setLineColor(Color.parseColor("#1E90FF"))//设置扫描线颜色
                .setLineSpeed(QrConfig.LINE_MEDIUM)//设置扫描线速度
                .setScanType(QrConfig.TYPE_BARCODE)//设置扫码类型（二维码，条形码，全部，自定义，默认为二维码）
                .setScanViewType(QrConfig.SCANVIEW_TYPE_QRCODE)//设置扫描框类型（二维码还是条形码，默认为二维码）
                .setCustombarcodeformat(QrConfig.BARCODE_PDF417)//此项只有在扫码类型为TYPE_CUSTOM时才有效
                .setPlaySound(true)//是否扫描成功后bi~的声音
                .setDingPath(R.raw.qrcode)//设置提示音(不设置为默认的Ding~)
                .setIsOnlyCenter(false)//是否只识别框中内容(默认为全屏识别)
                .setTitleText("")//设置Tilte文字
                .setTitleBackgroudColor(Color.parseColor("#262020"))//设置状态栏颜色
                .setTitleTextColor(Color.WHITE)//设置Title文字颜色
                .setShowZoom(false)//是否开始滑块的缩放
                .setAutoZoom(false)//是否开启自动缩放(实验性功能，不建议使用)
                .setFingerZoom(false)//是否开始双指缩放
                .setDoubleEngine(false)//是否开启双引擎识别(仅对识别二维码有效，并且开启后只识别框内功能将失效)
                .setScreenOrientation(QrConfig.SCREEN_PORTRAIT)//设置屏幕方式
                .setOpenAlbumText("选择要识别的图片")//打开相册的文字
                .setLooperScan(true)//是否连续扫描二维码
                .setLooperWaitTime(5 * 1000)//连续扫描间隔时间
                .setScanLineStyle(ScanLineView.style_line)//扫描线样式
                .setAutoLight(false)//自动灯光
                .setShowVibrator(false)//是否震动提醒
                .create();

        initParm();

        cp = findViewById(cn.bertsir.zbar.R.id.cp);
        //bi~
        soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
        soundPool.load(this, QrConfig.getDing_path(), 1);

        sv = findViewById(cn.bertsir.zbar.R.id.sv);
        sv.setType(options.getScan_view_type());

//        mo_scanner_back = (ImageView) findViewById(cn.bertsir.zbar.R.id.mo_scanner_back);
//        mo_scanner_back.setOnClickListener(this);
//        mo_scanner_back.setImageResource(options.getBackImgRes());

        iv_flash = findViewById(cn.bertsir.zbar.R.id.iv_flash);
//        iv_flash.setOnClickListener(this);
//        iv_flash.setImageResource(options.getLightImageRes());


        iv_album = findViewById(cn.bertsir.zbar.R.id.iv_album);
//        iv_album.setOnClickListener(this);
//        iv_album.setImageResource(options.getAblumImageRes());

        tv_des = findViewById(cn.bertsir.zbar.R.id.tv_des);

        vsb_zoom = findViewById(cn.bertsir.zbar.R.id.vsb_zoom);

        iv_album.setVisibility(options.isShow_light() ? View.VISIBLE : View.GONE);
        iv_flash.setVisibility(options.isShow_light() ? View.VISIBLE : View.GONE);
        iv_album.setVisibility(options.isShow_album() ? View.VISIBLE : View.GONE);
        tv_des.setVisibility(options.isShow_des() ? View.VISIBLE : View.GONE);
        vsb_zoom.setVisibility(options.isShow_zoom() ? View.VISIBLE : View.GONE);

        tv_des.setText(options.getDes_text());

        sv.setCornerColor(options.getCORNER_COLOR());
        sv.setLineSpeed(options.getLine_speed());
        sv.setLineColor(options.getLINE_COLOR());
        sv.setScanLineStyle(options.getLine_style());

        tvMemberNameValue = find(R.id.tvMemberNameValue);
        tvReadBookValue = find(R.id.tvReadBookValue);
        tvReadDayValue = find(R.id.tvReadDayValue);

        if (members != null) {
            tvMemberNameValue.setText(members.getFullName());
            tvReadBookValue.setText(String.valueOf(NepUtil.nullToZero(members.getReadBooks())));
            tvReadDayValue.setText(String.valueOf(NepUtil.nullToZero(members.getReadDays())));
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            setSeekBarColor(vsb_zoom, options.getCORNER_COLOR());
        }
        vsb_zoom.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                cp.setZoom((progress / 100f));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    /**
     * 初始化参数
     */
    private void initParm() {
        switch (options.getSCREEN_ORIENTATION()) {
            case QrConfig.SCREEN_LANDSCAPE:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                break;
            case QrConfig.SCREEN_PORTRAIT:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                break;
            case QrConfig.SCREEN_SENSOR:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
                break;
            default:
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                break;
        }
        Symbol.scanType = options.getScan_type();
        Symbol.scanFormat = options.getCustombarcodeformat();
        Symbol.is_only_scan_center = options.isOnly_center();
        Symbol.is_auto_zoom = options.isAuto_zoom();
        Symbol.doubleEngine = options.isDouble_engine();
        Symbol.looperScan = options.isLoop_scan();
        Symbol.looperWaitTime = options.getLoop_wait_time();
        Symbol.screenWidth = QRUtils.getInstance().getScreenWidth(this);
        Symbol.screenHeight = QRUtils.getInstance().getScreenHeight(this);
        if (options.isAuto_light()) {
            getSensorManager();
        }
    }

    /**
     * 获取光线传感器
     */
    public void getSensorManager() {
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager != null) {
            sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    public void setSeekBarColor(SeekBar seekBar, int color) {
        seekBar.getThumb().setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
        seekBar.getProgressDrawable().setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    }

    /**
     * 识别结果回调
     */
    private ScanCallback resultCallback = new ScanCallback() {
        @Override
        public void onScanResult(ScanResult result) {
            if (options.isPlay_sound()) {
                soundPool.play(1, 1, 1, 0, 0, 1);
            }
            if (options.isShow_vibrator()) {
                QRUtils.getInstance().getVibrator(getApplicationContext());
            }

            if (cp != null) {
                cp.setFlash(false);
            }
//            QrManager.getInstance().getResultCallback().onScanSuccess(result);
//            if (!Symbol.looperScan) {
//                finish();
//            }
//            Log.e(TAG, "onScanSuccess: " + result);
//            Toast.makeText(getApplicationContext(), "内容：" + result.getContent() + "  类型：" + result.getType(), Toast.LENGTH_SHORT).show();

            presenter.saveMemberReadBookLog2(storeUid, members.getUid(), result.getContent());
        }
    };

    @Override
    public void saveMemberReadBookLogOk(BaseBean<String> baseBean) {
        if (baseBean.success()) {
            MyToastUtils.showLong("读书记录添加成功！");
            finish();
        } else {
            MyToastUtils.showLong(baseBean.getMsg());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (cp != null) {
            cp.setScanCallback(resultCallback);
            cp.start();
        }

        if (sensorManager != null) {
            //一般在Resume方法中注册
            /**
             * 第三个参数决定传感器信息更新速度
             * SensorManager.SENSOR_DELAY_NORMAL:一般
             * SENSOR_DELAY_FASTEST:最快
             * SENSOR_DELAY_GAME:比较快,适合游戏
             * SENSOR_DELAY_UI:慢
             */
            sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (cp != null) {
            cp.stop();
        }
        if (sensorManager != null) {
            //解除注册
            sensorManager.unregisterListener(this, sensor);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (cp != null) {
            cp.setFlash(false);
            cp.stop();
        }
        soundPool.release();
    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

}
